// var root = "http://localhost/xskq/public"
const app = getApp()

// 接口地址

function interfaceUrl() {
  // return "http://localhost/xskq/public"
  return "http://81.70.97.193/xskq/public"
}

// var request = function (url, data = {}, method = "GET") {
var request = function (obj) {
  let {
    url,
    data = [],
    method = "GET",
    hideLoading = false
  } = obj
  if (!hideLoading) {
    wx.showLoading({
      title: '请稍后...',
      mask: true
    })
  }

  return new Promise((resolve, reject) => {
    const token = app.globalData.token
    // console.log(token)
    const header = {
      'content-type': method.toUpperCase() == "POST" ? 'application/x-www-form-urlencoded' : 'application/json',
    }
    if (token) {
      header["Cookie"] = "PHPSESSID=" + token
    }
    wx.request({
      method: method,
      url: interfaceUrl() + url,
      method: method,
      data: data,
      header,
      method: method.toUpperCase(),
      dataType: 'json',
      success: res => {
        !hideLoading && wx.hideLoading()
        // console.log(res)
        if (res.statusCode != 200 || res.data.error === true) {
          wx.showModal({
            title: '操作失败',
            cancelColor: res.data.msg || '服务器端发生错误',
            showCancel: false,
            success(res) {}
          })
          reject()
        } else {
          resolve(res.data)
        }
      },
      fail: res => {
        !hideLoading && wx.hideLoading()
        wx.showToast({
          title: '访问服务器失败',
          content: res.errMsg,
          icon: "none"
        })
        reject()
      }
    })
  })

}

export default request